package CountDownLatch_5;
import java.util.concurrent.CountDownLatch;

public class 多阶段任务处理_分阶段并行计算 {
    public static void main(String[] args) throws InterruptedException {
        final int WORKER_COUNT = 8;
        final int PHASE_COUNT = 3;

        // 每个阶段一个门闩
        final CountDownLatch[] phaseLatches = new CountDownLatch[PHASE_COUNT];
        for (int i = 0; i < PHASE_COUNT; i++) {
            phaseLatches[i] = new CountDownLatch(WORKER_COUNT);
        }

        // 创建工作线程
        for (int i = 0; i < WORKER_COUNT; i++) {
            final int workerId = i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        // 阶段1
                        System.out.println("Worker-" + workerId + " 开始阶段1");
                        Thread.sleep((long)(Math.random() * 500));
                        System.out.println("Worker-" + workerId + " 完成阶段1");
                        phaseLatches[0].countDown();
                        phaseLatches[0].await(); // 等待所有worker完成阶段1

                        // 阶段2
                        System.out.println("Worker-" + workerId + " 开始阶段2");
                        Thread.sleep((long)(Math.random() * 800));
                        System.out.println("Worker-" + workerId + " 完成阶段2");
                        phaseLatches[1].countDown();
                        phaseLatches[1].await(); // 等待所有worker完成阶段2

                        // 阶段3
                        System.out.println("Worker-" + workerId + " 开始阶段3");
                        Thread.sleep((long)(Math.random() * 300));
                        System.out.println("Worker-" + workerId + " 完成阶段3");
                        phaseLatches[2].countDown();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        // 等待所有阶段完成
        for (int i = 0; i < PHASE_COUNT; i++) {
            phaseLatches[i].await();
            System.out.println("所有worker已完成阶段 " + (i+1));
        }

        System.out.println("所有阶段任务已完成");
    }
}